from tkinter import messagebox, ttk
import os
from calc_utils import convert_to_pixels, convert_from_pixels, calculate_optimal_dpi_for_image


class DpiSizeMixin:
    def update_dpi_state(self):
        """更新DPI相关控件的状态和值"""
        if self.dpi_enabled.get():
            self.dpi_entry.configure(state="normal")

            # 检查图片尺寸和DPI的统一性
            _, uniform_width, uniform_height, uniform_dpi, uniform_size = self.check_images_uniformity()

            # 判断是否是尺寸相同但DPI不同的情况
            is_same_size_diff_dpi = uniform_size and not uniform_dpi and len(self.selected_files) > 1

            # 保存当前DPI值（如果存在）用于后续计算
            try:
                if self.dpi_var.get().strip():
                    current_dpi = float(self.dpi_var.get())
                    if current_dpi > 0:
                        self.last_used_dpi = current_dpi
                else:
                    # 如果DPI输入框为空但勾选了启用DPI，使用原始DPI
                    if hasattr(self, 'original_dpi'):
                        current_dpi = float(self.original_dpi)
                        self.last_used_dpi = current_dpi
            except ValueError:
                pass

            # 获取DPI值和单位
            dpi_value = self.dpi_var.get().strip()
            current_unit = self.unit_var.get()
            has_dpi_value = dpi_value != ""

            # 特殊处理尺寸相同但DPI不同的情况 - 仅当保持原图比例被勾选时
            if is_same_size_diff_dpi and self.maintain_ratio.get():
                if current_unit == "pixel":
                    # 像素单位下：只有当DPI有值时才禁用宽高输入框
                    if has_dpi_value:
                        self.width_var.set("")
                        self.height_var.set("")
                        self.width_entry.configure(state="disabled")
                        self.height_entry.configure(state="disabled")
                    else:
                        # DPI为空时，显示像素值且允许输入
                        if self.size_enabled.get():
                            self.width_entry.configure(state="normal")
                            self.height_entry.configure(state="normal")
                            # 显示原始像素尺寸（因为像素相同）
                            if hasattr(self, 'original_width') and hasattr(self, 'original_height'):
                                self.width_var.set(str(self.original_width))
                                self.height_var.set(str(self.original_height))
                elif current_unit == "cm" or current_unit == "inch":
                    # 厘米和英寸单位下：保持宽高输入框可用，像单张图片一样处理
                    if self.size_enabled.get():
                        self.width_entry.configure(state="normal")
                        self.height_entry.configure(state="normal")

                    # 只有当DPI有值时才显示物理尺寸
                    if has_dpi_value:
                        # 计算物理尺寸
                        self.adjust_size_for_dpi_change()
                    else:
                        # DPI为空时不显示值
                        self.width_var.set("")
                        self.height_var.set("")
            else:
                # 其他所有情况：保持宽高输入框的正常状态
                if self.size_enabled.get():
                    self.width_entry.configure(state="normal")
                    self.height_entry.configure(state="normal")

            # 当启用DPI修改时，立即调整尺寸（移除单位判断）
            if (self.maintain_ratio.get() and
                    hasattr(self, 'original_width') and
                    hasattr(self, 'original_height') and
                    hasattr(self, 'original_dpi')):
                # 让尺寸跟随DPI变化
                self.adjust_size_for_dpi_change()
        else:
            self.dpi_entry.configure(state="disabled")
            # 当取消勾选时,恢复原始DPI值
            if self.original_dpi is not None:
                # 检查DPI是否统一
                _, _, _, uniform_dpi, _ = self.check_images_uniformity()

                # 只有在DPI统一或只有一张图片时才显示具体数值
                if uniform_dpi or len(self.selected_files) <= 1:
                    self.dpi_var.set(str(int(self.original_dpi)))
                    # 如果有last_used_dpi属性，更新它
                    if hasattr(self, 'last_used_dpi'):
                        self.last_used_dpi = float(self.original_dpi)
                else:
                    # 如果DPI不统一，清空输入框
                    self.dpi_var.set("")

            # 恢复宽高输入框的正常状态
            if self.size_enabled.get():
                self.width_entry.configure(state="normal")
                self.height_entry.configure(state="normal")

        # 更新预览以反映DPI变化
        self.update_size_preview()

    def on_size_modified(self, *args):
        """当用户修改尺寸输入框时调用"""
        # 检查新值是否与原始值不同
        if (self.original_width is not None and
                self.original_height is not None and
                (self.width_var.get() != str(self.original_width) or
                 self.height_var.get() != str(self.original_height))):
            self.size_modified = True
        else:
            self.size_modified = False
        self.update_size_preview()

    def update_size_preview(self, name: str = "", index: str = "", mode: str = "") -> None:
        """更新尺寸预览显示

        Args:
            name: 变量名称，由 tkinter 传入，默认为空字符串
            index: 变量索引，由 tkinter 传入，默认为空字符串
            mode: 变更模式，由 tkinter 传入，默认为空字符串

        Returns:
            None: 函数不返回任何值，只更新界面显示
        """
        try:
            if not self.all_images_info:
                return

            # 特殊处理标准尺寸模式
            if self.is_standard_size_mode():
                self.update_standard_size_preview()
                return

            dpi_value, uniform_width, uniform_height, uniform_dpi, uniform_size = self.check_images_uniformity()
            total_files = len(self.selected_files)

            # 检查是否是尺寸相同但DPI不同的情况
            is_same_size_diff_dpi = uniform_size and not uniform_dpi and len(self.selected_files) > 1

            # DPI显示逻辑
            if self.dpi_enabled.get():
                # 检查用户设置的DPI是否与原图DPI相同
                try:
                    user_dpi = float(self.dpi_var.get()) if self.dpi_var.get() else 0
                    if abs(user_dpi - float(self.original_dpi)) < 0.1:  # 允许小误差
                        dpi_text = f"DPI: {self.dpi_var.get()} (原图)"
                    else:
                        dpi_text = f"DPI: {self.dpi_var.get()} (用户设定)"
                except (ValueError, TypeError):
                    dpi_text = f"DPI: {self.dpi_var.get()} (用户设定)"
                # 修复：检查DPI是否为空
                dpi_value = self.dpi_var.get().strip()
                current_dpi = float(dpi_value) if dpi_value else float(self.original_dpi)
            else:
                if uniform_dpi:
                    dpi_text = f"DPI: {int(self.original_dpi)} (原图)"
                    current_dpi = float(self.original_dpi)
                else:
                    dpi_text = "批量图片的DPI均不同"
                    # 使用默认DPI值进行计算
                    current_dpi = 72.0

            # 修改尺寸显示逻辑,处理批量不同尺寸的情况
            size_text = ""
            if not uniform_size:
                size_text = "批量图片的尺寸均不同 - 未修改的尺寸将保持原图数值"
                # 如果用户已经输入了某个值,显示已修改的部分
                modified_width = self.width_var.get().strip()
                modified_height = self.height_var.get().strip()

                if modified_width or modified_height:
                    size_text += "\n已设置:"
                    if modified_width:
                        size_text += f" 宽度={modified_width}{self.unit_var.get()}"
                    if modified_height:
                        size_text += f" 高度={modified_height}{self.unit_var.get()}"
            elif is_same_size_diff_dpi and self.maintain_ratio.get():
                # 尺寸相同但DPI不同且开启了保持原图比例
                if self.unit_var.get() == "pixel":
                    # 像素单位下：无论是否输入DPI，都显示前两张图片的关系式
                    if len(self.all_images_info) >= 2:
                        # 获取前两张图片信息
                        img1 = self.all_images_info[0]
                        img2 = self.all_images_info[1]

                        # 获取原始像素尺寸
                        img1_width_px = float(img1['width'])
                        img1_height_px = float(img1['height'])
                        img2_width_px = float(img2['width'])
                        img2_height_px = float(img2['height'])

                        # 获取DPI
                        img1_dpi = float(img1['dpi'])
                        img2_dpi = float(img2['dpi'])

                        # 计算厘米尺寸
                        img1_width_cm = (img1_width_px / img1_dpi) * 2.54
                        img1_height_cm = (img1_height_px / img1_dpi) * 2.54
                        img2_width_cm = (img2_width_px / img2_dpi) * 2.54
                        img2_height_cm = (img2_height_px / img2_dpi) * 2.54

                        # 如果用户输入了DPI，计算新的像素尺寸
                        if dpi_value:
                            new_dpi = current_dpi
                            img1_new_width_px = int(img1_width_cm / 2.54 * new_dpi)
                            img1_new_height_px = int(img1_height_cm / 2.54 * new_dpi)
                            img2_new_width_px = int(img2_width_cm / 2.54 * new_dpi)
                            img2_new_height_px = int(img2_height_cm / 2.54 * new_dpi)

                            # 显示用户设定DPI下的关系式
                            file1_name = os.path.basename(img1['path'])
                            file2_name = os.path.basename(img2['path'])
                            size_text = f"图片尺寸相同但DPI不同 - 前两张图片关系式:\n"
                            size_text += f"{file1_name}: {img1_width_cm:.2f}厘米 × {img1_height_cm:.2f}厘米 = {img1_new_width_px}像素 × {img1_new_height_px}像素\n"
                            size_text += f"{file2_name}: {img2_width_cm:.2f}厘米 × {img2_height_cm:.2f}厘米 = {img2_new_width_px}像素 × {img2_new_height_px}像素"
                        else:
                            # 检查是否用户修改了像素尺寸
                            width_str = self.width_var.get().strip()
                            height_str = self.height_var.get().strip()

                            # 如果用户输入了有效的像素值
                            if width_str and height_str and width_str.isdigit() and height_str.isdigit():
                                # 获取用户输入的新像素尺寸
                                user_width_px = float(width_str)
                                user_height_px = float(height_str)

                                # 计算缩放比例
                                width_scale = user_width_px / img1_width_px
                                height_scale = user_height_px / img1_height_px

                                # 按照相同比例缩放第二张图片
                                new_img2_width_px = int(img2_width_px * width_scale)
                                new_img2_height_px = int(img2_height_px * height_scale)

                                # 根据新像素值重新计算厘米尺寸（保持原DPI）
                                new_img1_width_cm = (user_width_px / img1_dpi) * 2.54
                                new_img1_height_cm = (user_height_px / img1_dpi) * 2.54
                                new_img2_width_cm = (new_img2_width_px / img2_dpi) * 2.54
                                new_img2_height_cm = (new_img2_height_px / img2_dpi) * 2.54

                                # 显示用户修改尺寸后的关系式
                                file1_name = os.path.basename(img1['path'])
                                file2_name = os.path.basename(img2['path'])
                                size_text = f"图片尺寸相同但DPI不同 - 前两张图片关系式(用户修改):\n"
                                size_text += f"{file1_name}: {new_img1_width_cm:.2f}厘米 × {new_img1_height_cm:.2f}厘米 = {int(user_width_px)}像素 × {int(user_height_px)}像素\n"
                                size_text += f"{file2_name}: {new_img2_width_cm:.2f}厘米 × {new_img2_height_cm:.2f}厘米 = {new_img2_width_px}像素 × {new_img2_height_px}像素"
                            else:
                                # 显示原始关系式
                                file1_name = os.path.basename(img1['path'])
                                file2_name = os.path.basename(img2['path'])
                                size_text = f"图片尺寸相同但DPI不同 - 前两张图片关系式:\n"
                                size_text += f"{file1_name}: {img1_width_cm:.2f}厘米 × {img1_height_cm:.2f}厘米 = {int(img1_width_px)}像素 × {int(img1_height_px)}像素\n"
                                size_text += f"{file2_name}: {img2_width_cm:.2f}厘米 × {img2_height_cm:.2f}厘米 = {int(img2_width_px)}像素 × {int(img2_height_px)}像素"
                    else:
                        size_text = "批量图片尺寸相同但DPI不同 - 无法显示关系式（图片数量不足）"
                elif self.dpi_enabled.get() and dpi_value:
                    # 厘米或英寸单位下，如果输入了DPI，显示与单张图片相同的关系式
                    # 获取当前输入的值
                    width_str = self.width_var.get().strip()
                    height_str = self.height_var.get().strip()

                    if width_str and height_str:
                        try:
                            # 高精度计算像素值
                            width_pixels_float = self.convert_to_pixels(width_str, self.unit_var.get(), current_dpi)
                            height_pixels_float = self.convert_to_pixels(height_str, self.unit_var.get(), current_dpi)

                            # 对显示值进行四舍五入为整数
                            width_pixels = int(round(width_pixels_float))
                            height_pixels = int(round(height_pixels_float))

                            # 构建显示文本
                            unit_display = "厘米" if self.unit_var.get() == "cm" else self.unit_var.get()
                            size_text = f"{width_str}{unit_display} × {height_str}{unit_display} (用户设定) = {width_pixels}像素 × {height_pixels}像素 (用户设定)"
                        except (ValueError, ZeroDivisionError):
                            size_text = "无法计算预览 - 输入值无效"
                    else:
                        # 计算原始物理尺寸
                        width_cm = (uniform_width / current_dpi) * 2.54
                        height_cm = (uniform_height / current_dpi) * 2.54
                        if self.unit_var.get() == "cm":
                            size_text = f"{width_cm:.2f}厘米 × {height_cm:.2f}厘米 (用户设定) = {uniform_width}像素 × {uniform_height}像素 (原图)"
                        else:  # inch
                            width_inch = width_cm / 2.54
                            height_inch = height_cm / 2.54
                            size_text = f"{width_inch:.2f}inch × {height_inch:.2f}inch (用户设定) = {uniform_width}像素 × {uniform_height}像素 (原图)"
                else:
                    # 厘米或英寸单位下，如果没有输入DPI，也显示前两张图片的关系式
                    if len(self.all_images_info) >= 2:
                        # 获取前两张图片信息
                        img1 = self.all_images_info[0]
                        img2 = self.all_images_info[1]

                        # 获取原始像素尺寸
                        img1_width_px = float(img1['width'])
                        img1_height_px = float(img1['height'])
                        img2_width_px = float(img2['width'])
                        img2_height_px = float(img2['height'])

                        # 获取DPI
                        img1_dpi = float(img1['dpi'])
                        img2_dpi = float(img2['dpi'])

                        # 计算厘米或英寸尺寸
                        if self.unit_var.get() == "cm":
                            img1_width_physical = (img1_width_px / img1_dpi) * 2.54
                            img1_height_physical = (img1_height_px / img1_dpi) * 2.54
                            img2_width_physical = (img2_width_px / img2_dpi) * 2.54
                            img2_height_physical = (img2_height_px / img2_dpi) * 2.54
                            unit_display = "厘米"
                        else:  # inch
                            img1_width_physical = img1_width_px / img1_dpi
                            img1_height_physical = img1_height_px / img1_dpi
                            img2_width_physical = img2_width_px / img2_dpi
                            img2_height_physical = img2_height_px / img2_dpi
                            unit_display = "inch"

                        # 显示关系式
                        file1_name = os.path.basename(img1['path'])
                        file2_name = os.path.basename(img2['path'])
                        size_text = f"图片尺寸相同但DPI不同 - 前两张图片关系式:\n"
                        size_text += f"{file1_name}: {img1_width_physical:.2f}{unit_display} × {img1_height_physical:.2f}{unit_display} = {int(img1_width_px)}像素 × {int(img1_height_px)}像素\n"
                        size_text += f"{file2_name}: {img2_width_physical:.2f}{unit_display} × {img2_height_physical:.2f}{unit_display} = {int(img2_width_px)}像素 × {int(img2_height_px)}像素"
                    else:
                        size_text = "批量图片尺寸相同但DPI不同 - 无法显示关系式（图片数量不足）"
            else:
                # 获取当前输入的值，使用原始输入而不是格式化后的值
                width_str = self.width_var.get().strip()
                height_str = self.height_var.get().strip()

                if width_str and height_str:
                    # 计算像素尺寸 - 为避免计算误差，直接使用原始像素值
                    try:
                        # 高精度计算像素值，然后对显示值进行四舍五入
                        width_pixels_float = self.convert_to_pixels(width_str, self.unit_var.get(), current_dpi)
                        height_pixels_float = self.convert_to_pixels(height_str, self.unit_var.get(), current_dpi)

                        # 对显示值进行四舍五入为整数
                        width_pixels = int(round(width_pixels_float))
                        height_pixels = int(round(height_pixels_float))

                        # 获取原始值用于比较
                        original_width_px = float(self.original_width)
                        original_height_px = float(self.original_height)
                        original_dpi = float(self.original_dpi)

                        # 计算原始物理尺寸
                        original_width_cm = (original_width_px / original_dpi) * 2.54
                        original_height_cm = (original_height_px / original_dpi) * 2.54
                        original_width_inch = original_width_px / original_dpi
                        original_height_inch = original_height_px / original_dpi

                        # 判断当前值是否接近原始值（像素允许0.5的误差，厘米允许0.01的误差，英寸允许0.005的误差）
                        is_width_px_original = abs(width_pixels_float - original_width_px) < 0.5
                        is_height_px_original = abs(height_pixels_float - original_height_px) < 0.5

                        # 根据当前单位判断输入值是否接近原始值
                        try:
                            if self.unit_var.get() == "cm":
                                is_width_physical_original = abs(float(width_str) - original_width_cm) < 0.01
                                is_height_physical_original = abs(float(height_str) - original_height_cm) < 0.01
                                # 计算用于显示的厘米尺寸
                                display_width_cm = float(width_str)
                                display_height_cm = float(height_str)
                            elif self.unit_var.get() == "inch":
                                is_width_physical_original = abs(float(width_str) - original_width_inch) < 0.005
                                is_height_physical_original = abs(float(height_str) - original_height_inch) < 0.005
                                # 计算用于显示的厘米尺寸
                                display_width_cm = float(width_str) * 2.54
                                display_height_cm = float(height_str) * 2.54
                            else:  # pixel
                                # 计算当前的物理尺寸
                                display_width_cm = (width_pixels_float / current_dpi) * 2.54
                                display_height_cm = (height_pixels_float / current_dpi) * 2.54
                                is_width_physical_original = abs(display_width_cm - original_width_cm) < 0.01
                                is_height_physical_original = abs(display_height_cm - original_height_cm) < 0.01
                        except ValueError:
                            # 如果转换失败，假设不是原始值
                            is_width_physical_original = False
                            is_height_physical_original = False
                            display_width_cm = 0
                            display_height_cm = 0

                        # 根据实际值的接近程度决定标签，不再考虑按钮状态
                        # 判断物理尺寸是否接近原始值
                        if is_width_physical_original and is_height_physical_original:
                            physical_label = "（原图）"
                        else:
                            if self.unit_var.get() == "pixel":
                                physical_label = "（用户设定）"
                            else:
                                physical_label = "（用户设定）"

                        # 判断像素尺寸是否接近原始值
                        if is_width_px_original and is_height_px_original:
                            pixel_label = "（原图）"
                        else:
                            if self.unit_var.get() == "pixel":
                                pixel_label = "（用户设定）"
                            else:
                                pixel_label = "（用户设定）"

                        # 构建显示文本
                        if self.unit_var.get() in ["cm", "inch"]:
                            unit_display = "厘米" if self.unit_var.get() == "cm" else self.unit_var.get()
                            size_text = f"{width_str}{unit_display} × {height_str}{unit_display} {physical_label}= {width_pixels}像素 × {height_pixels}像素 {pixel_label}"
                        else:
                            # 像素单位模式
                            if self.unit_var.get() == "pixel":
                                size_text = f"{display_width_cm:.2f}厘米 × {display_height_cm:.2f}厘米 {physical_label}= {width_pixels}像素 × {height_pixels}像素 {pixel_label}"
                            else:
                                unit_display = "厘米" if self.unit_var.get() == "cm" else self.unit_var.get()
                                size_text = f"{width_str}{unit_display} × {height_str}{unit_display} {physical_label}= {width_pixels}像素 × {height_pixels}像素 {pixel_label}"
                    except (ValueError, ZeroDivisionError):
                        size_text = "无法计算预览 - 输入值无效"
                else:
                    # 如果是原始尺寸，转换为厘米显示
                    width_cm = (uniform_width / current_dpi) * 2.54
                    height_cm = (uniform_height / current_dpi) * 2.54
                    size_text = f"{width_cm:.2f}厘米 × {height_cm:.2f}厘米 （原图）= {uniform_width}像素 × {uniform_height}像素 （原图）"

            # 添加文件数量信息
            if self.mode_var.get() == "folder":
                self.preview_label.configure(
                    text=f"{dpi_text}\n{size_text}\n处理文件数: {total_files}"
                )
            else:
                self.preview_label.configure(text=f"{dpi_text}\n{size_text}")

        except ValueError as e:
            self.preview_label.configure(text=f"输入无效: {str(e)}")
        except Exception as e:
            self.preview_label.configure(text=f"预览更新错误: {str(e)}")

    def update_size_display(self):
        try:
            old_unit = self.unit_var.get()  # 保存旧单位以进行比较

            # 获取DPI值
            dpi_str = self.dpi_var.get().strip()
            has_dpi_value = dpi_str != ""
            dpi = float(dpi_str) if has_dpi_value else (
                float(self.original_dpi) if hasattr(self, 'original_dpi') and self.original_dpi is not None else 72.0)

            # 标记当前正在更新单位，避免触发其他回调
            self._updating_unit = True

            try:
                # 检查图片尺寸和DPI的统一性
                uniform_format, uniform_width, uniform_height, uniform_dpi, uniform_size = self.check_images_uniformity()

                # 判断是否是尺寸相同但DPI不同的情况
                is_same_size_diff_dpi = uniform_size and not uniform_dpi and len(self.selected_files) > 1

                # 处理不同的单位切换情况
                new_unit = self.unit_var.get()

                # 特殊处理批量保持比例模式
                if self.batch_maintain_ratio.get() and self.size_enabled.get():
                    # 获取当前宽高值
                    width_str = self.width_var.get().strip()
                    height_str = self.height_var.get().strip()

                    # 如果已有输入，则转换该输入；如果无输入，保持输入框为空
                    if width_str and not height_str:
                        # 只有宽度有值，转换宽度
                        try:
                            width_value = float(width_str)
                            if old_unit == "pixel" and new_unit in ["cm", "inch"]:
                                if new_unit == "cm":
                                    width_cm = (width_value / dpi) * 2.54
                                    self.width_var.set(f"{width_cm:.2f}" if width_cm > 0.01 else "")
                                else:  # inch
                                    width_inch = width_value / dpi
                                    self.width_var.set(f"{width_inch:.2f}" if width_inch > 0.01 else "")
                            elif old_unit in ["cm", "inch"] and new_unit == "pixel":
                                width_pixels = self.convert_to_pixels(width_value, old_unit, dpi)
                                self.width_var.set(str(int(width_pixels)) if width_pixels > 0 else "")
                            elif old_unit == "cm" and new_unit == "inch":
                                width_inch = width_value / 2.54
                                self.width_var.set(f"{width_inch:.2f}" if width_inch > 0.01 else "")
                            elif old_unit == "inch" and new_unit == "cm":
                                width_cm = width_value * 2.54
                                self.width_var.set(f"{width_cm:.2f}" if width_cm > 0.01 else "")
                        except ValueError:
                            pass
                        # 确保高度保持为空
                        self.height_var.set("")
                    elif height_str and not width_str:
                        # 只有高度有值，转换高度
                        try:
                            height_value = float(height_str)
                            if old_unit == "pixel" and new_unit in ["cm", "inch"]:
                                if new_unit == "cm":
                                    height_cm = (height_value / dpi) * 2.54
                                    self.height_var.set(f"{height_cm:.2f}" if height_cm > 0.01 else "")
                                else:  # inch
                                    height_inch = height_value / dpi
                                    self.height_var.set(f"{height_inch:.2f}" if height_inch > 0.01 else "")
                            elif old_unit in ["cm", "inch"] and new_unit == "pixel":
                                height_pixels = self.convert_to_pixels(height_value, old_unit, dpi)
                                self.height_var.set(str(int(height_pixels)) if height_pixels > 0 else "")
                            elif old_unit == "cm" and new_unit == "inch":
                                height_inch = height_value / 2.54
                                self.height_var.set(f"{height_inch:.2f}" if height_inch > 0.01 else "")
                            elif old_unit == "inch" and new_unit == "cm":
                                height_cm = height_value * 2.54
                                self.height_var.set(f"{height_cm:.2f}" if height_cm > 0.01 else "")
                        except ValueError:
                            pass
                        # 确保宽度保持为空
                        self.width_var.set("")
                    else:
                        # 两个都没有值或两个都有值（不应该在批量比例模式下出现）
                        # 清空两个输入框，让用户重新选择
                        self.width_var.set("")
                        self.height_var.set("")

                    # 立即更新输入框状态
                    self.update_batch_ratio_state()

                    # 处理完批量保持比例模式后直接返回，不执行后续的常规处理
                    return

                # 以下是原有代码的其他条件处理...

                # 如果保持原图比例被勾选
                elif self.maintain_ratio.get() and self.size_enabled.get():
                    if old_unit == "pixel" and new_unit in ["cm", "inch"]:
                        # 从像素切换到厘米/英寸：保持物理尺寸不变
                        # 将尺寸从像素转换为物理单位
                        original_width_px = float(self.original_width)
                        original_height_px = float(self.original_height)

                        if new_unit == "cm":
                            # 转换为厘米
                            width_cm = (original_width_px / dpi) * 2.54
                            height_cm = (original_height_px / dpi) * 2.54
                            self.width_var.set(f"{width_cm:.2f}")
                            self.height_var.set(f"{height_cm:.2f}")
                        else:  # inch
                            # 转换为英寸
                            width_inch = original_width_px / dpi
                            height_inch = original_height_px / dpi
                            self.width_var.set(f"{width_inch:.2f}")
                            self.height_var.set(f"{height_inch:.2f}")

                    elif new_unit == "pixel" and old_unit in ["cm", "inch"]:
                        # 从厘米/英寸切换到像素：保持像素不变
                        # 直接显示原始像素尺寸
                        self.width_var.set(str(self.original_width))
                        self.height_var.set(str(self.original_height))

                    elif old_unit in ["cm", "inch"] and new_unit in ["cm", "inch"]:
                        # 在厘米和英寸之间切换：转换物理尺寸
                        # 先获取当前值
                        width_str = self.width_var.get().strip()
                        height_str = self.height_var.get().strip()

                        if width_str and height_str:
                            width_value = float(width_str)
                            height_value = float(height_str)

                            if old_unit == "cm" and new_unit == "inch":
                                # 厘米转英寸
                                width_inch = width_value / 2.54
                                height_inch = height_value / 2.54
                                self.width_var.set(f"{width_inch:.2f}")
                                self.height_var.set(f"{height_inch:.2f}")
                            elif old_unit == "inch" and new_unit == "cm":
                                # 英寸转厘米
                                width_cm = width_value * 2.54
                                height_cm = height_value * 2.54
                                self.width_var.set(f"{width_cm:.2f}")
                                self.height_var.set(f"{height_cm:.2f}")

                else:
                    # 保持比例未勾选或尺寸修改未启用时的一般转换
                    # 先转换为像素
                    try:
                        width_pixels = self.convert_to_pixels(self.width_var.get(), old_unit, dpi)
                        height_pixels = self.convert_to_pixels(self.height_var.get(), old_unit, dpi)

                        # 再从像素转换为新单位
                        new_width = self.convert_from_pixels(width_pixels, new_unit, dpi)
                        new_height = self.convert_from_pixels(height_pixels, new_unit, dpi)

                        # 更新显示
                        self.width_var.set(f"{new_width:.2f}")
                        self.height_var.set(f"{new_height:.2f}")
                    except (ValueError, TypeError):
                        # 如果转换失败，直接使用原始尺寸
                        if new_unit == "pixel":
                            self.width_var.set(str(self.original_width))
                            self.height_var.set(str(self.original_height))
                        else:
                            # 转换原始像素为物理尺寸
                            if new_unit == "cm":
                                width_cm = (self.original_width / dpi) * 2.54
                                height_cm = (self.original_height / dpi) * 2.54
                                self.width_var.set(f"{width_cm:.2f}")
                                self.height_var.set(f"{height_cm:.2f}")
                            else:  # inch
                                width_inch = self.original_width / dpi
                                height_inch = self.original_height / dpi
                                self.width_var.set(f"{width_inch:.2f}")
                                self.height_var.set(f"{height_inch:.2f}")

            finally:
                # 删除标记
                if hasattr(self, '_updating_unit'):
                    delattr(self, '_updating_unit')

            # 检查是否切换到了像素单位，且需要根据DPI调整尺寸
            if (new_unit == "pixel" and
                    self.maintain_ratio.get() and
                    self.dpi_enabled.get() and
                    self.size_enabled.get()):
                # 延迟执行调整尺寸的逻辑，确保状态已更新
                self.root.after(10, self.adjust_size_for_dpi_change)
            # 检查是否切换到了厘米/英寸单位，且需要根据尺寸调整DPI
            elif (new_unit in ["cm", "inch"] and
                  self.maintain_ratio.get() and
                  self.dpi_enabled.get() and
                  self.size_enabled.get()):
                # 延迟执行调整DPI的逻辑
                self.root.after(10, self.adjust_size_for_dpi_change)

            self.update_size_preview()
        except ValueError:
            pass

        # 检查是否进入或退出特殊模式，并应用规则
        is_special_mode = (self.batch_maintain_ratio.get() and
                           not self.resampling_enabled.get() and
                           self.unit_var.get() in ["cm", "inch"] and
                           self.size_enabled.get())
        if is_special_mode:
            self._apply_special_mode_rules()
        elif self.batch_maintain_ratio.get() and self.size_enabled.get():
            # 如果不是特殊模式，但仍是普通批量模式，则更新批量模式状态
            self.update_batch_ratio_state()
        # 自动调整窗口高度
        self.adjust_window_height()

    def adjust_size_for_dpi_change(self, *args):
        if getattr(self, '_block_auto_update_size', False):
            return
        """当DPI变化时的响应方法

        在像素单位下：调整尺寸以保持物理尺寸不变
        在厘米/英寸单位下：
            - 重新采样开启时：DPI变化不影响尺寸值，DPI和尺寸值各自独立修改
            - 重新采样关闭时：保持像素不变，调整物理尺寸
        """
        # 确保原始尺寸和DPI值已存在
        if (not hasattr(self, 'original_width') or
                not hasattr(self, 'original_height') or
                not hasattr(self, 'original_dpi')):
            return

        # 如果批量保持比例被勾选，则不进行这里的自动调整
        # 批量保持比例通过process_batch_ratio处理，确保每张图片独立处理
        if self.batch_maintain_ratio.get():
            return

        # 只在勾选了保持原图比例、DPI修改已启用、尺寸修改已启用时处理
        if not (self.maintain_ratio.get() and
                self.dpi_enabled.get() and
                self.size_enabled.get()):
            return

        # 检查图片尺寸和DPI的统一性
        uniform_format, uniform_width, uniform_height, uniform_dpi, uniform_size = self.check_images_uniformity()

        # 对于尺寸相同但DPI不同的图片，特殊处理
        is_same_size_diff_dpi = uniform_size and not uniform_dpi and len(self.selected_files) > 1

        # 如果正在进行比例计算，延迟DPI调整以避免冲突
        if hasattr(self, '_in_proportion_calculation'):
            self.root.after(150, lambda: self.adjust_size_for_dpi_change(*args))
            return

        # 获取DPI值和单位及重新采样状态
        dpi_value = self.dpi_var.get().strip()
        current_unit = self.unit_var.get()
        has_dpi_value = dpi_value != ""
        is_resampling = self.resampling_enabled.get()

        # 当尺寸相同DPI不同的图片，勾选重新采样，且单位为厘米或英寸时，
        # DPI变化不应影响宽高值
        if is_same_size_diff_dpi and is_resampling and current_unit != "pixel":
            return

        try:
            # 获取新的DPI值
            try:
                new_dpi_str = self.dpi_var.get().strip()
                if not new_dpi_str:
                    # DPI为空时的特殊处理
                    if is_same_size_diff_dpi and self.maintain_ratio.get():
                        if current_unit == "pixel":
                            # 像素单位下，允许输入并显示原始像素尺寸
                            if self.size_enabled.get():
                                self.width_entry.configure(state="normal")
                                self.height_entry.configure(state="normal")
                                self.width_var.set(str(self.original_width))
                                self.height_var.set(str(self.original_height))
                        else:
                            # 非像素单位下，清空值但保持输入框可用
                            self.width_var.set("")
                            self.height_var.set("")
                            if self.size_enabled.get():
                                self.width_entry.configure(state="normal")
                                self.height_entry.configure(state="normal")
                    return

                # 处理用户输入的整数DPI值
                try:
                    # 尝试先转换为整数，如果是整数值就使用整数
                    new_dpi_int = int(new_dpi_str)
                    if float(new_dpi_str) == float(new_dpi_int):
                        new_dpi = new_dpi_int
                    else:
                        new_dpi = float(new_dpi_str)
                except ValueError:
                    # 不是整数，直接使用浮点数
                    new_dpi = float(new_dpi_str)

                if new_dpi <= 0:
                    return

                # 检查是否恢复到原始DPI值
                if abs(new_dpi - float(self.original_dpi)) < 0.001:
                    # 如果是原始DPI，直接使用原始尺寸，避免任何计算误差
                    if self.unit_var.get() == "pixel":
                        # 像素单位模式：直接设置原始像素值
                        new_width_px = self.original_width
                        new_height_px = self.original_height
                        self.width_var.set(str(new_width_px))
                        self.height_var.set(str(new_height_px))
                    else:
                        # 厘米或英寸单位模式：计算原始物理尺寸
                        original_dpi = float(self.original_dpi)
                        if self.unit_var.get() == "cm":
                            # 转换为厘米
                            width_cm = (self.original_width / original_dpi) * 2.54
                            height_cm = (self.original_height / original_dpi) * 2.54
                            self.width_var.set(f"{width_cm:.2f}")
                            self.height_var.set(f"{height_cm:.2f}")
                        else:  # inch
                            # 转换为英寸
                            width_inch = self.original_width / original_dpi
                            height_inch = self.original_height / original_dpi
                            self.width_var.set(f"{width_inch:.2f}")
                            self.height_var.set(f"{height_inch:.2f}")

                    self.last_used_dpi = float(self.original_dpi)
                    self.size_modified = False
                    self.update_size_preview()
                    return
            except ValueError:
                return

            # 防止递归调用
            if hasattr(self, '_updating_dpi'):
                return
            self._updating_dpi = True

            try:
                # 获取当前单位
                current_unit = self.unit_var.get()
                # 直接使用原始尺寸和原始DPI作为基准计算
                original_width_px = float(self.original_width)
                original_height_px = float(self.original_height)
                original_dpi = float(self.original_dpi)

                # 只有在特定条件下特殊处理尺寸相同但DPI不同的图片
                if is_same_size_diff_dpi and self.maintain_ratio.get():
                    if current_unit == "pixel":
                        # 像素单位下：有DPI值时禁用宽高输入框
                        if has_dpi_value:
                            self.width_var.set("")
                            self.height_var.set("")
                            self.width_entry.configure(state="disabled")
                            self.height_entry.configure(state="disabled")
                        else:
                            # DPI为空时，允许输入并显示原始像素值
                            if self.size_enabled.get():
                                self.width_entry.configure(state="normal")
                                self.height_entry.configure(state="normal")
                                self.width_var.set(str(self.original_width))
                                self.height_var.set(str(self.original_height))
                    elif current_unit == "cm" or current_unit == "inch":
                        # 厘米和英寸单位下：和单张图片一样处理，保持宽高输入框可用
                        if self.size_enabled.get():
                            self.width_entry.configure(state="normal")
                            self.height_entry.configure(state="normal")

                        # 有DPI值时，计算物理尺寸
                        if has_dpi_value:
                            if current_unit == "cm":
                                width_cm = (original_width_px / new_dpi) * 2.54
                                height_cm = (original_height_px / new_dpi) * 2.54

                                # 检查是否为用户输入，如果是，不改变宽度和高度
                                if not self.user_input_width:
                                    self.width_var.set(f"{width_cm:.2f}")
                                if not self.user_input_height:
                                    self.height_var.set(f"{height_cm:.2f}")
                            else:  # inch
                                width_inch = original_width_px / new_dpi
                                height_inch = original_height_px / new_dpi

                                # 检查是否为用户输入，如果是，不改变宽度和高度
                                if not self.user_input_width:
                                    self.width_var.set(f"{width_inch:.2f}")
                                if not self.user_input_height:
                                    self.height_var.set(f"{height_inch:.2f}")
                        else:
                            # DPI为空时不显示值，但保持输入框可用
                            if not self.user_input_width:
                                self.width_var.set("")
                            if not self.user_input_height:
                                self.height_var.set("")
                    else:
                        # 英寸单位下：根据DPI情况处理
                        if has_dpi_value:
                            # 有DPI值时，启用宽高输入框并显示物理尺寸
                            self.width_entry.configure(state="normal")
                            self.height_entry.configure(state="normal")

                            # 计算物理尺寸
                            width_inch = original_width_px / new_dpi
                            height_inch = original_height_px / new_dpi
                            self.width_var.set(f"{width_inch:.2f}")
                            self.height_var.set(f"{height_inch:.2f}")
                        else:
                            # DPI为空时只清空显示，但保持输入框可用
                            if self.size_enabled.get():
                                self.width_entry.configure(state="normal")
                                self.height_entry.configure(state="normal")
                            self.width_var.set("")
                            self.height_var.set("")
                elif current_unit == "pixel":
                    # 【像素模式】：保持物理尺寸不变，调整像素尺寸
                    # 计算物理尺寸（英寸）- 使用原始值
                    width_inch = original_width_px / original_dpi
                    height_inch = original_height_px / original_dpi

                    # 使用新DPI和原始物理尺寸精确计算新像素尺寸
                    new_width_px = int(width_inch * new_dpi)
                    new_height_px = int(height_inch * new_dpi)

                    # 确保尺寸至少为1像素
                    new_width_px = max(1, new_width_px)
                    new_height_px = max(1, new_height_px)

                    # 检查是否为用户输入，如果是，不改变宽度和高度
                    if not self.user_input_width:
                        self.width_var.set(str(new_width_px))
                    if not self.user_input_height:
                        self.height_var.set(str(new_height_px))

                    # 此处不重置用户输入标志，保持用户输入优先级
                else:
                    # 【厘米/英寸模式】
                    # 如果重新采样开启，DPI变化不影响尺寸值，各自独立修改
                    # 如果重新采样关闭，保持像素不变，调整物理尺寸
                    if not is_resampling:
                        # 未启用重新采样：保持像素不变，调整物理尺寸
                        # 计算新的物理尺寸
                        if current_unit == "cm":
                            # 转换为厘米：像素 / DPI * 2.54
                            width_cm = (original_width_px / new_dpi) * 2.54
                            height_cm = (original_height_px / new_dpi) * 2.54

                            # 检查是否为用户输入，如果是，不改变宽度和高度
                            if not self.user_input_width:
                                # 注意：对于自动计算的值，使用2位小数格式化
                                self.width_var.set(f"{width_cm:.2f}")
                            if not self.user_input_height:
                                self.height_var.set(f"{height_cm:.2f}")
                        else:  # inch
                            # 转换为英寸：像素 / DPI
                            width_inch = original_width_px / new_dpi
                            height_inch = original_height_px / new_dpi

                            # 检查是否为用户输入，如果是，不改变宽度和高度
                            if not self.user_input_width:
                                self.width_var.set(f"{width_inch:.2f}")
                            if not self.user_input_height:
                                self.height_var.set(f"{height_inch:.2f}")
                    # 如果启用了重新采样，则不自动调整尺寸值
                    # 即：不做任何处理，保持用户输入的尺寸值不变

                # 保存当前使用的DPI值，用于预览显示
                self.last_used_dpi = new_dpi

                # 设置修改标志
                self.size_modified = True

                # 更新物理尺寸预览
                self.update_size_preview()

            finally:
                # 移除递归保护标志
                delattr(self, '_updating_dpi')

        except Exception as e:
            print(f"调整DPI尺寸时出错: {e}")
            # 处理其他可能的异常

    def adjust_dpi_for_size_change(self, *args):
        if getattr(self, '_block_auto_update_size', False):
            return
        """当厘米/英寸尺寸变化时，调整DPI以保持像素不变（仅在重新采样关闭时生效）"""
        # 如果重新采样开启，不调整DPI以保持像素不变
        if self.resampling_enabled.get():
            return

        # 如果正在更新单位或DPI，不要触发调整
        if hasattr(self, '_updating_unit') or hasattr(self, '_updating_dpi'):
            return

        # 如果正在进行比例计算，延迟DPI调整以避免冲突
        if hasattr(self, '_in_proportion_calculation'):
            self.root.after(150, lambda: self.adjust_dpi_for_size_change(*args))
            return

        # 只在勾选了保持原图比例、厘米或英寸单位、DPI修改已启用、尺寸修改已启用时处理
        current_unit = self.unit_var.get()
        if not (self.maintain_ratio.get() and
                current_unit in ["cm", "inch"] and
                self.dpi_enabled.get() and
                self.size_enabled.get()):
            return

        # 确保原始尺寸和DPI值已存在
        if (not hasattr(self, 'original_width') or
                not hasattr(self, 'original_height') or
                not hasattr(self, 'original_dpi')):
            return

        # 防止递归调用
        if hasattr(self, '_updating_size_for_dpi'):
            return
        self._updating_size_for_dpi = True

        try:
            # 获取输入的值
            width_str = self.width_var.get().strip()
            height_str = self.height_var.get().strip()

            # 确定哪个值被修改了
            modified_field = None
            if args and args[0] == str(self.width_var):
                modified_field = "width"
            elif args and args[0] == str(self.height_var):
                modified_field = "height"
            else:
                return  # 没有识别到变化的字段

            # 获取原始像素尺寸
            original_width_px = float(self.original_width)
            original_height_px = float(self.original_height)
            original_dpi = float(self.original_dpi)

            # 根据修改的字段计算新DPI
            new_dpi = 0

            if modified_field == "width" and width_str:
                try:
                    # 将输入的物理尺寸转换为对应单位的值
                    width_value = float(width_str)

                    # 计算新的DPI
                    if current_unit == "cm":
                        # 厘米转英寸再计算DPI: 像素 / (厘米 / 2.54)
                        new_dpi = original_width_px / (width_value / 2.54)
                    else:  # inch
                        # 直接计算: 像素 / 英寸
                        new_dpi = original_width_px / width_value
                except ValueError:
                    return

            elif modified_field == "height" and height_str:
                try:
                    # 将输入的物理尺寸转换为对应单位的值
                    height_value = float(height_str)

                    # 计算新的DPI
                    if current_unit == "cm":
                        # 厘米转英寸再计算DPI: 像素 / (厘米 / 2.54)
                        new_dpi = original_height_px / (height_value / 2.54)
                    else:  # inch
                        # 直接计算: 像素 / 英寸
                        new_dpi = original_height_px / height_value
                except ValueError:
                    return

            # 确保DPI有效
            if new_dpi <= 0:
                return

            # 检查计算出的DPI是否非常接近原始DPI（处理浮点数精度问题）
            # 如果差异小于0.5%，则使用原始DPI值
            if abs(new_dpi - original_dpi) / original_dpi < 0.005:
                new_dpi = original_dpi

            # 检查是否为用户输入，如果是，不改变DPI
            if not self.user_input_dpi:
                # 记录用户修改了哪个值，用于显示DPI
                self.last_modified_field = modified_field
                self.last_user_input_value = width_str if modified_field == "width" else height_str

                # 对于自动计算的DPI值，根据不同情况决定精度
                if self.size_modified:
                    # 检查是否是整数DPI值或接近整数值
                    if abs(new_dpi - round(new_dpi)) < 0.01:
                        # 非常接近整数，使用整数显示
                        self.dpi_var.set(str(int(round(new_dpi))))
                    else:
                        # 如果用户已修改尺寸，使用两位小数格式
                        # 这确保用户输入的厘米/英寸值被合理保留，同时避免过多小数位
                        self.dpi_var.set(f"{new_dpi:.3f}")
                else:
                    # 对于首次计算或恢复原始尺寸的情况，使用更友好的显示格式
                    if new_dpi >= 100:
                        # 大于等于100的DPI值使用整数
                        self.dpi_var.set(str(int(round(new_dpi))))
                    else:
                        # 小于100的DPI值保留两位小数
                        self.dpi_var.set(f"{new_dpi:.3f}")

            # 此处不重置用户输入标志，保持用户输入优先级

            # 设置标记，防止adjust_size_for_dpi_change再次触发
            self._updating_dpi = True
            # 延迟一会儿删除标记
            self.root.after(100, self.clear_updating_dpi)

            # 更新预览
            self.update_size_preview()

        finally:
            # 移除递归保护标志
            delattr(self, '_updating_size_for_dpi')

    def clear_updating_dpi(self):
        """清除_updating_dpi标记"""
        if hasattr(self, '_updating_dpi'):
            delattr(self, '_updating_dpi')

    def on_ratio_change(self):
        """当用户勾选或取消勾选保持原图比例选项时调用"""
        # 检查图片尺寸和DPI的统一性
        uniform_format, uniform_width, uniform_height, uniform_dpi, uniform_size = self.check_images_uniformity()

        # 判断是否是尺寸相同但DPI不同的情况
        is_same_size_diff_dpi = uniform_size and not uniform_dpi and len(self.selected_files) > 1

        # 获取DPI值和单位
        dpi_value = self.dpi_var.get().strip()
        current_unit = self.unit_var.get()
        has_dpi_value = dpi_value != ""

        # 检查重新采样状态
        # 如果重新采样关闭且取消勾选保持原图比例，并且批量保持比例也未勾选
        # 则自动开启重新采样，因为不重新采样模式只在保持原图比例或批量保持比例勾选时有效
        if not self.resampling_enabled.get() and not self.maintain_ratio.get() and not self.batch_maintain_ratio.get():
            self.resampling_enabled.set(True)
            messagebox.showinfo("提示",
                                "已自动开启重新采样模式。\n不重新采样模式仅在勾选'保持原图比例'或'批量保持比例'时有效。")
            # 更新重新采样状态
            self.update_resampling_state()
            return

        # 如果是尺寸相同但DPI不同，且勾选了保持原图比例并启用了DPI修改
        if is_same_size_diff_dpi and self.maintain_ratio.get() and self.dpi_enabled.get():
            if current_unit == "pixel":
                # 像素单位：只有当DPI有值时才禁用宽高输入框
                if has_dpi_value:
                    # 禁用宽高输入框并清空内容
                    self.width_var.set("")
                    self.height_var.set("")
                    self.width_entry.configure(state="disabled")
                    self.height_entry.configure(state="disabled")
                else:
                    # DPI为空时，允许输入并显示原始像素值
                    if self.size_enabled.get():
                        self.width_entry.configure(state="normal")
                        self.height_entry.configure(state="normal")
                        self.width_var.set(str(self.original_width))
                        self.height_var.set(str(self.original_height))
            else:
                # 非像素单位：根据DPI情况处理
                if not has_dpi_value:
                    # DPI为空时，禁用输入并清空显示
                    self.width_entry.configure(state="disabled")
                    self.height_entry.configure(state="disabled")
                    self.width_var.set("")
                    self.height_var.set("")
                else:
                    # 有DPI值时，启用输入并显示物理尺寸
                    self.width_entry.configure(state="normal")
                    self.height_entry.configure(state="normal")
                    # 调用DPI调整方法，计算并显示物理尺寸
                    self.root.after(10, self.adjust_size_for_dpi_change)
            # 更新预览显示
            self.update_size_preview()
        # 如果取消勾选保持原图比例，恢复宽高输入框状态
        elif not self.maintain_ratio.get() and is_same_size_diff_dpi and self.size_enabled.get():
            # 恢复宽高输入框状态
            self.width_entry.configure(state="normal")
            self.height_entry.configure(state="normal")
            # 恢复为原始尺寸
            self.width_var.set(str(self.original_width))
            self.height_var.set(str(self.original_height))
            self.update_size_preview()
        # 常规情况处理
        elif self.maintain_ratio.get() and self.dpi_enabled.get() and self.size_enabled.get():
            # 根据当前单位执行不同操作
            if current_unit == "pixel":
                # 像素单位：调整尺寸以匹配DPI变化
                # 延迟执行以确保状态已更新
                self.root.after(10, self.adjust_size_for_dpi_change)
            else:
                # 厘米/英寸单位：保持像素不变，根据当前DPI更新物理尺寸
                self.root.after(10, self.adjust_size_for_dpi_change)

    def reset_user_input_flags(self):
        """重置用户输入标志，允许程序再次进行自动计算"""
        self.user_input_width = False
        self.user_input_height = False
        self.user_input_dpi = False

        # 重置标志后立即触发一次计算，确保所有值同步
        if self.maintain_ratio.get() and self.size_enabled.get():
            # 延迟执行计算，确保标志重置已完成
            self.root.after(100, self.recalculate_all_values)

    def recalculate_all_values(self):
        """重新计算所有相关值，确保同步"""
        # 确保原始尺寸和DPI值已存在
        if (not hasattr(self, 'original_width') or
                not hasattr(self, 'original_height') or
                not hasattr(self, 'original_dpi')):
            return

        # 防止递归调用
        if hasattr(self, '_recalculating_all'):
            return

        self._recalculating_all = True

        try:
            current_unit = self.unit_var.get()

            # 根据当前单位触发适当的计算
            if current_unit == "pixel":
                # 像素单位：根据DPI调整尺寸
                self.adjust_size_for_dpi_change()
            else:
                # 厘米/英寸单位：先检查哪个值被修改过
                if getattr(self, 'last_modified_field', None) == "width":
                    # 如果宽度被修改，根据宽度计算高度和DPI
                    width_var_name = str(self.width_var)
                    self.calculate_proportional_size(width_var_name)
                    self.adjust_dpi_for_size_change(width_var_name)
                else:
                    # 否则根据高度计算宽度和DPI
                    height_var_name = str(self.height_var)
                    self.calculate_proportional_size(height_var_name)
                    self.adjust_dpi_for_size_change(height_var_name)

            # 更新预览
            self.update_size_preview()
        finally:
            # 移除递归保护标志
            delattr(self, '_recalculating_all')

    def delayed_reset_flags(self):
        """延迟重置用户输入标志，但保持当前焦点输入框的标志"""
        # 获取当前焦点的控件
        focus_widget = self.root.focus_get()

        # 确保没有正在进行的计算
        if hasattr(self, '_updating_size') or hasattr(self, '_updating_dpi') or hasattr(self, '_updating_size_for_dpi'):
            # 如果有计算正在进行，再次延迟尝试
            self.root.after(100, self.delayed_reset_flags)
            return

        # 只重置未获得焦点的控件对应的标志
        if focus_widget != self.width_entry:
            self.user_input_width = False

        if focus_widget != self.height_entry:
            self.user_input_height = False

        if focus_widget != self.dpi_entry:
            self.user_input_dpi = False

    def verify_calculations(self):
        """验证计算结果是否合理，避免快速输入导致的错误"""
        # 如果不需要保持比例，或尺寸修改被禁用，则不处理
        if not self.maintain_ratio.get() or not self.size_enabled.get():
            return

        # 防止递归调用
        if hasattr(self, '_verifying_calculations'):
            return

        self._verifying_calculations = True

        try:
            # 获取当前单位和DPI
            current_unit = self.unit_var.get()
            dpi_var_value = self.dpi_var.get().strip()

            if not dpi_var_value:
                return

            try:
                current_dpi = float(dpi_var_value)
                if current_dpi <= 0:
                    return
            except ValueError:
                return

            # 检查DPI值是否异常（根据您的描述，10160是一个非常异常的值）
            original_dpi = float(self.original_dpi)
            if current_dpi > original_dpi * 10 or current_dpi < original_dpi / 10:
                # DPI值异常，重置并重新计算
                print(f"检测到异常DPI值: {current_dpi}，重新计算...")
                self.reset_user_input_flags()
                self.recalculate_all_values()
                return

            # 获取宽度和高度
            width_str = self.width_var.get().strip()
            height_str = self.height_var.get().strip()

            if not width_str or not height_str:
                return

            try:
                # 将当前尺寸转换为像素
                width_px = self.convert_to_pixels(width_str, current_unit, current_dpi)
                height_px = self.convert_to_pixels(height_str, current_unit, current_dpi)

                # 计算原始宽高比
                original_ratio = float(self.original_height) / float(self.original_width)
                current_ratio = height_px / width_px

                # 检查比例是否严重偏离（超过10%）
                if abs(original_ratio - current_ratio) / original_ratio > 0.1:
                    # 比例异常，重置并重新计算
                    print(f"检测到异常比例: 原始 {original_ratio:.4f}, 当前 {current_ratio:.4f}，重新计算...")
                    self.reset_user_input_flags()
                    self.recalculate_all_values()
            except (ValueError, ZeroDivisionError):
                pass
        finally:
            delattr(self, '_verifying_calculations')


    pass
